﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Web;
using TNO.Education.Helpers;
using System.Web.Caching;

namespace TNO.Education.SearchStdScore
{
    public partial class SearchStdScoreUserControl : BaseControl
    {

        #region Properties

        private SearchStdScore _webPart;
        public SearchStdScore WebPart
        {
            get
            {
                if (_webPart == null)
                    _webPart = this.Parent as SearchStdScore;
                return _webPart;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUniversityCombo();
                LoadBlockCombo();

                // Get request query strings
                string univeNumber = Page.Request.QueryString["u"];

                if (!string.IsNullOrEmpty(univeNumber))
                {
                    string blockNumber = Page.Request.QueryString["b"];

                    ddlUniversity.SelectedValue = univeNumber;
                    ddlBlock.SelectedValue = blockNumber;

                    btnSearch_Click(btnSearch, e);
                }
                else
                {
                    LayoutNotification();
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pnlResult.Controls.Clear();

            if (string.IsNullOrEmpty(ddlUniversity.SelectedValue))
            {
                using (HtmlHelper htmlHelper = new HtmlHelper())
                {
                    htmlHelper.AddClass("error-tcdc");
                    htmlHelper.WriteLine(HtmlTag.Div, "Bạn chưa chọn trường cần xem điểm chuẩn");
                    pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
                }
            }
            else
            {
                string key = this.BaseUrl + '_' + ddlUniversity.SelectedValue + '_' + ddlBlock.SelectedValue;
                object obj = HttpContext.Current.Cache[key];
                lock (this)
                {
                    if (obj == null)
                    {
                        obj = DataHelper.GetStdScore(ddlUniversity.SelectedValue, ddlBlock.SelectedValue, WebPart.Year);
                        HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(CacheMinutes), TimeSpan.Zero, CacheItemPriority.Default, null);
                    }
                }

                LayoutSearchResult(obj as DataTable);
            }
        }

        #endregion

        #region Methods

        private void LoadUniversityCombo()
        {
            string key = this.BaseUrl + '_' + Fields.University.TableName;
            object obj = HttpContext.Current.Cache[key];

            lock (this)
            {
                if (obj == null)
                {
                    obj = DataHelper.GetStdUniversity(WebPart.Year);
                    HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(CacheMinutes), TimeSpan.Zero, CacheItemPriority.Default, null);
                }
            }

            ddlUniversity.DataSource = obj as DataTable;
            ddlUniversity.DataTextField = Fields.University.Title;
            ddlUniversity.DataValueField = Fields.University.Id;
            ddlUniversity.DataBind();
        }

        private void LoadBlockCombo()
        {
            string key = this.BaseUrl + '_' + Fields.Block.TableName;
            object obj = HttpContext.Current.Cache[key];

            lock (this)
            {
                if (obj == null)
                {
                    obj = DataHelper.GetBlocks();
                    HttpContext.Current.Cache.Add(key, obj, null, DateTime.Now.AddMinutes(CacheMinutes), TimeSpan.Zero, CacheItemPriority.Default, null);
                }
            }

            ddlBlock.DataSource = obj as DataTable;
            ddlBlock.DataTextField = Fields.Block.Name;
            ddlBlock.DataValueField = Fields.Block.Id;
            ddlBlock.DataBind();
        }

        /// <summary>
        /// Have number new universities.
        /// </summary>
        private void LayoutNotification()
        {
            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                htmlHelper.AddClass("error-details");
                using (htmlHelper.RenderTag(HtmlTag.Div))
                {
                    // Number of universities - 1 (Select a university)
                    htmlHelper.WriteLine(string.Format(@"Đã có <span class='r'>{0}</span> trường công bố điểm chuẩn năm {1}.",
                        ddlUniversity.Items.Count - 1, WebPart.Year));
                    using (htmlHelper.RenderTag(HtmlTag.Span))
                    {
                        htmlHelper.AddAttribute("alt", "diem chuan moi");
                        htmlHelper.AddAttribute("src", "/_layouts/images/TNO.Education/New.gif");
                        htmlHelper.WriteLine(HtmlTag.Img);
                    }
                }

                this.pnlResult.Controls.Clear();
                this.pnlResult.Controls.Add(new LiteralControl(htmlHelper.ToString()));
            }
        }

        private void LayoutSearchResult(DataTable table)
        {
            using (HtmlHelper htmlHelper = new HtmlHelper())
            {
                string msg = string.Format("Điểm chuẩn của trường: <span class='r'>{0} - {1}</span>.", ddlUniversity.SelectedItem.Text, ddlUniversity.SelectedValue);
                if (ddlBlock.SelectedValue != string.Empty)
                {
                    msg += string.Format(" Khối thi: <span class='r'>{0}</span>.", ddlBlock.SelectedValue);
                }

                htmlHelper.AddClass("msg-tcdc");
                htmlHelper.WriteLine(HtmlTag.Div, msg);

                if (table.Rows.Count > 0)
                {
                    htmlHelper.AddAttribute("cellspacing", "1");
                    htmlHelper.AddClass("grid-table");
                    using (htmlHelper.WriteTag(HtmlTag.Table))
                    {
                        using (htmlHelper.RenderTag("thead"))
                        {
                            using (htmlHelper.RenderTag(HtmlTag.Tr))
                            {
                                htmlHelper.WriteLine(HtmlTag.Th, "STT");
                                htmlHelper.WriteLine(HtmlTag.Th, "Mã ngành");
                                htmlHelper.WriteLine(HtmlTag.Th, "Tên ngành");
                                htmlHelper.WriteLine(HtmlTag.Th, "Khối thi");
                                htmlHelper.WriteLine(HtmlTag.Th, "Điểm chuẩn");
                                htmlHelper.WriteLine(HtmlTag.Th, "Ghi chú");
                            }
                        }
                        using (htmlHelper.RenderTag("tbody"))
                        {
                            int i = 1;
                            foreach (DataRow item in table.Rows)
                            {
                                using (htmlHelper.WriteTag(HtmlTag.Tr))
                                {
                                    htmlHelper.AddClass("td-01");
                                    htmlHelper.WriteLine(HtmlTag.Td, (i++).ToString());
                                    htmlHelper.AddClass("td-02");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.StdScore.MaNganh].ToString());
                                    htmlHelper.AddClass("td-03");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.StdScore.TenNganh].ToString());
                                    htmlHelper.AddClass("td-04");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.StdScore.KhoiThi].ToString());
                                    htmlHelper.AddClass("td-05");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.StdScore.Diem].ToString());
                                    htmlHelper.AddClass("td-06");
                                    htmlHelper.WriteLine(HtmlTag.Td, item[Fields.StdScore.Note].ToString());
                                }
                            }
                        }
                    }
                }
                else
                {
                    htmlHelper.AddClass("error-tcdc");
                    htmlHelper.WriteLine(HtmlTag.Div, "Không tìm thấy kết quả.");
                }
                pnlResult.Controls.Add(new Literal { Text = htmlHelper.ToString() });
            }
        }

        #endregion

    }
}